package com.zt.teacher.service.impl;

import com.zt.common.common.ApiException;
import com.zt.common.common.CodeMsg;
import com.zt.common.pojo.ActiveClass;
import com.zt.common.pojo.homework.Homework;
import com.zt.common.pojo.homework.HomeworkAnswer;
import com.zt.common.utils.JwtUtil;
import com.zt.teacher.dao.HomeworkDao;
import com.zt.teacher.dto.HomeworkInfoDTO;
import com.zt.teacher.dto.HomeworkWithClassDTO;
import com.zt.teacher.dto.SummaryDTO;
import com.zt.teacher.service.ActiveClassService;
import com.zt.teacher.service.HomeworkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * description:
 * author:zt
 * date:2022-02-10
 */
@Service
@Transactional
public class HomeworkServiceImpl implements HomeworkService {

    @Autowired
    private HomeworkDao homeworkDao;
    @Autowired
    @Lazy
    private ActiveClassService activeClassService;

    /**
     * 老师发布作业 新增homework
     */
    @Override
    public int insert(Homework homework) {
        //插入一条作业记录
        homework.setCreateTime(new Date());
        homeworkDao.insert(homework);
        return homework.getId();
    }

    /**
     * @param classId 班级id
     * @return 该班级发布的作业
     */
    @Override
    public List<Homework> getByClassId(HttpServletRequest request, int classId) {
        String teacherId = JwtUtil.decodedGetID(request.getHeader("Authorization"));
        ActiveClass activeClass = activeClassService.getClassById(classId);
        //如果该课堂不是该老师上的课，则抛异常
        if (!activeClass.getTeacherId().equals(teacherId)) throw new ApiException(CodeMsg.CLASS_NOT_BELONG);
        return homeworkDao.getByClassId(classId);
    }

    @Override
    public ArrayList<HomeworkInfoDTO> getHomeworkAndAnswer(HttpServletRequest request, int classId){
        List<Homework> homeworkList = getByClassId(request,classId);

        ArrayList<HomeworkInfoDTO> res = new ArrayList<>();
        for (Homework h : homeworkList) {
            HomeworkInfoDTO homeworkInfoDTO = new HomeworkInfoDTO().setId(h.getId()).setName(h.getName()).setCreateTime(h.getCreateTime()).setDeadline(h.getDeadline()).
                    setQuestion(h.getQuestion()).setClassId(h.getClassId()).setSubmitted(h.getAnswers().size()).
                    setChecked((int) h.getAnswers().stream().filter(a -> a.getPoint() != -1).count());

            res.add(homeworkInfoDTO);
        }
        return res;
    }

    /**
     * @param request 获取teacherId
     * @return 返回该老师的课堂和作业概况
     */
    @Override
    public List<HomeworkWithClassDTO> getBySemester(HttpServletRequest request, String semester){
        String teacherId = JwtUtil.decodedGetID(request.getHeader("Authorization"));

        List<HomeworkWithClassDTO> homeworkWithClassDTOS = homeworkDao.getBySemester(teacherId, semester);
        homeworkWithClassDTOS.forEach(h -> {
            //设置是否已完成批改参数
            if (h.getAnswers().size() == 0) h.setChecked(true);
            else
                h.setChecked(h.getAnswers().size() <= h.getAnswers().stream().filter(answer -> answer.getPoint() != -1).count());
        });
        return homeworkWithClassDTOS;
    }

    /**
     * @param homeworkId 作业Id
     * @return 返回该作业以及学生回答情况
     */
    @Override
    public Homework getByHomeworkId(HttpServletRequest request, int homeworkId){
        Homework homework = homeworkDao.getByHomeworkId(homeworkId);

        String teacherId = JwtUtil.decodedGetID(request.getHeader("Authorization"));
        ActiveClass activeClass = activeClassService.getClassById(homework.getClassId());
        if (!activeClass.getTeacherId().equals(teacherId)) throw new ApiException(CodeMsg.CLASS_NOT_BELONG);

        return homework;
    }

    @Override
    public void delete(HttpServletRequest request, int homeworkId){
        int homeworkClassId = homeworkDao.getByHomeworkId(homeworkId).getClassId();

        String teacherId = JwtUtil.decodedGetID(request.getHeader("Authorization"));
        ActiveClass activeClass = activeClassService.getClassById(homeworkClassId);
        if (!activeClass.getTeacherId().equals(teacherId)) throw new ApiException(CodeMsg.CLASS_NOT_BELONG);

        homeworkDao.delete(homeworkId);
    }

    @Override
    public void markHomework(HttpServletRequest request, HomeworkAnswer homeworkAnswer) {
        String teacherId = JwtUtil.decodedGetID(request.getHeader("Authorization"));

        ActiveClass activeClass = activeClassService.getClassById(homeworkDao.getByHomeworkId(homeworkAnswer.getHomeworkId()).getClassId());
        if (!activeClass.getTeacherId().equals(teacherId)) throw new ApiException(CodeMsg.CLASS_NOT_BELONG);

        homeworkDao.update(homeworkAnswer);
    }

    /**
     * @param classId 班级id
     * @return 获取该班级所有作业作答情况
     */
    @Override
    public List<SummaryDTO> getSummaryByClassId(int classId){
        ArrayList<SummaryDTO> res = new ArrayList<>();

        List<Homework> homeworkList = homeworkDao.getByClassId(classId);
        for (Homework homework : homeworkList) {
            //平均分计算 已打分的分数累计/已打分的学生人数
            double totalScore = 0; int count = 0;
//            double totalScore = homework.getAnswers().stream().mapToDouble(HomeworkAnswer::getPoint).sum();
            for (HomeworkAnswer h : homework.getAnswers()) {
                if (h.getPoint() != -1){
                    totalScore += h.getPoint();
                    count ++;
                }
            }
            res.add(new SummaryDTO(homework.getId(), homework.getName(),count==0?0:totalScore/count));
        }
        return res;
    }

    @Override
    public HomeworkAnswer getScoreByStuId(String studentId, int homeworkId){
        return homeworkDao.getByHomeworkIdAndStuId(studentId,homeworkId);
    }
}
